package com.xymtop.Controller;

import com.xymtop.Annotation.Controller;
import com.xymtop.Annotation.Mapping;
import com.xymtop.Annotation.Rest;
import com.xymtop.Entity.MyClass;
import com.xymtop.Entity.TheClass;
import com.xymtop.Server.ResoultJson;
import com.xymtop.Service.TheClassService;
import com.xymtop.Server.Util.DBService;
import com.xymtop.Server.Util.Time;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @ClassName : TheClassController
 * @Description : 班级控制器
 * @Author : 肖叶茂
 * @Date: 2022/12/13  17:42
 */
@Controller(router = "class")
public class TheClassController extends HttpServlet {
    private TheClassService theClassService = new TheClassService();
    @Rest
    @Mapping(url = "getList")
    public ResoultJson<Object> getList(HttpServletRequest request, HttpServletResponse response) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        if(request.getParameter("major") != null) {
            List<Object> objects = theClassService.getList(request.getParameter("major"));
            if (objects == null) {
                return new ResoultJson<>(204);
            } else {
                return new ResoultJson<>(0, objects, "");
            }
        }else {
            List<Object> objects = DBService.Get("SELECT * FROM `javaweb`.`class`", TheClass.class.getCanonicalName());
            if(objects.isEmpty()){
                return new ResoultJson<>(204);
            }else{
                return new ResoultJson<>(0,objects,"");
            }

        }
    }


    @Rest
    @Mapping(url = "add")
    public ResoultJson<String> add(HttpServletRequest request,HttpServletResponse response) throws ClassNotFoundException, IllegalAccessException {
        String name = request.getParameter("name");
        String teacher = request.getParameter("teacher");
        String major = request.getParameter("major");
        String phone = request.getParameter("phone");

       MyClass theClass = new MyClass();

       theClass.id = Time.getUnixTime();
       theClass.code = "1";
       theClass.teacher = teacher;
       theClass.name = name;
       theClass.phone = phone;
       theClass.major = major;


        if(DBService.InsertObject(theClass,"class")){
            return new ResoultJson<>(200);
        }else {
            return new ResoultJson<>(204);
        }
    }
}
